package com.cherrypt.api.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cherrypt.api.core.dao.RoleDao;
import com.cherrypt.api.core.service.RoleService;
import com.cherrypt.api.model.dataobject.Role;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author intent
 * @date 2019/8/4 13:22
 * @about <link href='http://zzyitj.xyz/'/>
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {
    private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private ListOperations<String, Object> listOperations;

    @Value("${api.config.redis.role.prefix}")
    private String rolePrefix;

    @Value("${api.config.redis.role.exp}")
    private long roleExp;

    @Override
    public List<Role> getRedisRoleListByUid(int uid) {
        List<Role> roleList = new ArrayList<>();
        List<Object> list = listOperations.range(rolePrefix + uid, 0, -1);
        if (list != null && list.size() > 0) {
            for (Object o : list) {
                roleList.add((Role) o);
            }
        }
        return roleList;
    }

    @Override
    public void saveRedisRoleList(int uid, List<Role> roleList) {
        roleList.forEach(role -> {
            listOperations.leftPush(rolePrefix + uid, role);
        });
    }

    @Override
    public List<Role> getRoleByUid(int uid) {
        List<Role> roleList = getRedisRoleListByUid(uid);
        if (roleList == null || roleList.size() == 0) {
            roleList = this.baseMapper.selectRoleByUid(uid);
            if (roleList.size() != 0) {
                saveRedisRoleList(uid, roleList);
                logger.info("缓存RoleList到Redis: {} {}", uid, roleList);
            }
        }
        return roleList;
    }
}
